package com.sea.operate.service.impl;


import com.codecrane.core.util.CommonUtils;
import com.codecrane.core.web.BatchImportUtils;
import com.sea.data.entity.Order;
import com.sea.data.entity.OrderDetail;
import com.sea.operate.entity.Related;
import com.sea.operate.mapper.RelatedMapper;
import com.sea.operate.service.RelatedService;
import com.sea.operate.service.RelatedSkuService;
import com.sea.product.entity.Channel;
import com.sea.product.entity.Product;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.List;


/**
 * @author 陈鸿飞
 */
@Service
public class RelatedServiceImpl implements RelatedService {

    @Autowired
    private RelatedMapper relatedMapper;
    @Autowired
    private RelatedSkuService relatedSkuService;

    @Override
    public List<Related> findByCnd(Related related) {
        return relatedMapper.findByCnd(related);
    }

    @Override
    public int save(Related related) {
        return relatedMapper.insert(related);
    }

    @Override
    public int usave(Related related) {
        return relatedMapper.update(related);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importRelated(InputStream inputStream, String fileName) throws Exception {
        Workbook workBook = BatchImportUtils.getWorkBook(inputStream, fileName);
        List<Sheet> sheets = BatchImportUtils.getSheets(workBook);
        if (null != sheets && sheets.size() > 0) {
            Sheet sheet = sheets.get(0);
            List<Related> list = BatchImportUtils.iteratorForRelated(sheet);
            if (null == list || list.size() == 0) {
                throw new Exception("请至少保存一条SKU信息！");
            } else {
                for(Related related:list){
                    Related rea = relatedMapper.findByAsin(related.getRelatedAsin(), related.getRelatedChannelName());
                    if(null==rea) {
                        save(related);
                    }else{
                        relatedMapper.updateListing(related);
                    }
                }
                relatedSkuService.updateListingName();
            }
        }
    }

    @Override
    public Related findByAsin(String relatedAsin,String relatedChannelName) {
        return relatedMapper.findByAsin(relatedAsin,relatedChannelName);
    }
}
